package com.xiao.community.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.xiao.community.entity.OrderEntity;
import com.xiao.community.feign.SeckilFeign;
import com.xiao.community.feign.UserFeign;
import com.xiao.community.service.OrderService;
import com.xiao.group.common.Vo.UsersEntity;
import com.xiao.group.common.utils.PageUtils;
import com.xiao.group.common.utils.R;
import org.apache.commons.lang.StringUtils;
import org.apache.lucene.search.TotalHits;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiao.group.common.utils.Query;

import com.xiao.community.dao.GoodsDao;
import com.xiao.community.entity.GoodsEntity;
import com.xiao.community.service.GoodsService;


@Service("goodsService")
public class GoodsServiceImpl extends ServiceImpl<GoodsDao, GoodsEntity> implements GoodsService {
    @Autowired
    RestHighLevelClient client;

    @Autowired
    GoodsService goodsService;

    @Autowired
    OrderService orderService;

    @Autowired
    UserFeign userFeign;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<GoodsEntity> page = this.page(
                new Query<GoodsEntity>().getPage(params),
                new QueryWrapper<GoodsEntity>()
        );

        return new PageUtils(page);
    }
    @Override
    public R toes(String mohu, Integer page, Integer size,Integer goodsId) throws IOException {
        SearchRequest searchRequest = new SearchRequest("shequ_es");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        // 模糊查询
        if(StringUtils.isNotBlank(mohu)){
            boolQueryBuilder.filter(QueryBuilders.matchQuery("goodsName",mohu));
        }
        if(goodsId!= null && goodsId!=0){
            boolQueryBuilder.filter(QueryBuilders.termQuery("goodsId",goodsId));
        }
        //分页
        searchSourceBuilder.from((page-1)*size);
        searchSourceBuilder.size(size);
        //高亮
        if(StringUtils.isNotBlank(mohu)){
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            HighlightBuilder.Field highlightTitle =
                    new HighlightBuilder.Field("goodsName");
            highlightTitle.highlighterType("unified");
            highlightBuilder.field(highlightTitle);
            highlightBuilder.preTags("<span style='color:red'>");
            highlightBuilder.postTags("</span>");


            searchSourceBuilder.highlighter(highlightBuilder);
        }
        searchSourceBuilder.query(boolQueryBuilder);
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = null;
        searchResponse   = client.search(searchRequest, RequestOptions.DEFAULT);
        SearchHits hits = searchResponse.getHits();
        TotalHits totalHits = hits.getTotalHits();
// the total number of hits, must be interpreted in the context of totalHits.relation
        long numHits = totalHits.value;
// whether the number of hits is accurate (EQUAL_TO) or a lower bound of the total (GREATER_THAN_OR_EQUAL_TO)
        TotalHits.Relation relation = totalHits.relation;
        float maxScore = hits.getMaxScore();
        SearchHit[] searchHits = hits.getHits();

        ArrayList<GoodsEntity> list = new ArrayList<>();
        for (SearchHit hit : searchHits) {
            // do something with the SearchHit
            String index = hit.getIndex();
            String id = hit.getId();
            float score = hit.getScore();
            String sourceAsString = hit.getSourceAsString();
            GoodsEntity goodsEntity = JSON.parseObject(sourceAsString, new TypeReference<GoodsEntity>() {
            });
            goodsEntity.setGoodsId(Integer.parseInt(id));

            //处理高亮
            if(StringUtils.isNotBlank(mohu)){
                    Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                    HighlightField highlight = highlightFields.get("goodsName");
                    Text[] fragments = highlight.fragments();
                    String fragmentString = fragments[0].string();
                    goodsEntity.setGoodsName(fragmentString);
            }
            list.add(goodsEntity);
        }
        PageUtils<GoodsEntity> goodsEntityPageUtils = new PageUtils<>(list, (int) numHits, page, size);
        return R.ok().put("data",goodsEntityPageUtils);
    }

    @Override
    public GoodsEntity findbygoodsid(Integer id) {
        return this.getById(id);
    }
    @Override
    public Integer goumai(Integer userid, Integer goodsid) {

        // 商品的库存 -1
        GoodsEntity goodsEntity = goodsService.getById(goodsid);
        goodsEntity.setGoodsKucun(goodsEntity.getGoodsKucun()-1);
        goodsService.updateById(goodsEntity);
        UsersEntity usersEntity = userFeign.info(userid);
        //生成 订单
        OrderEntity orderEntity = new OrderEntity();
        //赋值用户
        orderEntity.setAdminId(userid);
        //赋值商品id
        orderEntity.setGoodsId(goodsid);
        //赋值商品名称
        orderEntity.setGoodsName(goodsEntity.getGoodsName());
        //赋值订单状态  创建订单的状态 0  支付成功后 回调修改状态
        orderEntity.setOrderStatus(0);
        //商品单价
        orderEntity.setGoodsPrice(goodsEntity.getGoodsPrice());
        //创建时间
        orderEntity.setCreateTime(new Date());
        //赋值 用户名称
        orderEntity.setUserName(usersEntity.getUsername());
        //支付时间  回调后修改支付时间

        //订单地址id
        boolean save = orderService.save(orderEntity);
        System.out.println(save+"状态是");
        return orderEntity.getId();
    }

    @Override
    public R tolist() {
        QueryWrapper<GoodsEntity> wrapper = new QueryWrapper<>();
        wrapper.ne("goods_status",1);
        wrapper.ne("goods_status",5);
        List<GoodsEntity> goodsEntities = baseMapper.selectList(wrapper);
        return R.ok().put("data",goodsEntities);
    }
    //砍价的商品列表
    @Override
    public R tolists() {
        QueryWrapper<GoodsEntity> wrapper = new QueryWrapper<>();
        //查询的时候 不查询拼团进行中 和拼团为开始
        wrapper.ne("goods_status",4);
        wrapper.ne("goods_status",5);
        List<GoodsEntity> goodsEntities = baseMapper.selectList(wrapper);
        return R.ok().put("data",goodsEntities);
    }

    @Autowired
    GoodsDao goodsDao;
    @Override
    public  List<GoodsEntity> togoodsList(String idss) {
         return goodsDao.togoodsList(idss);
    }
    @Autowired
    SeckilFeign seckilFeign;
    @Override
    public R togoodslists() {
        ArrayList<GoodsEntity> list1 = new ArrayList<>();
        List<GoodsEntity> list = baseMapper.selectList(null);
        for (GoodsEntity goodsEntity : list) {
            boolean toinfo = seckilFeign.toinfo(goodsEntity.getGoodsId());
            if(toinfo){
                list1.add(goodsEntity);
            }
        }
        return R.ok().put("data",list1);
    }

    @Scheduled(cron = "0/60 * * * * ?")
    public  void  toes() throws IOException {
        //批量存入到 es中
        BulkRequest bulkRequest = new BulkRequest();
        List<GoodsEntity> goodsEntities = baseMapper.selectList(null);
        for (GoodsEntity goodsEntity : goodsEntities) {
            IndexRequest request = new IndexRequest("shequ_es");
            request.id(goodsEntity.getGoodsId().toString());
            String jsonString = JSON.toJSONString(goodsEntity);
            request.source(jsonString, XContentType.JSON);
            bulkRequest.add(request);
        }
        client.bulk(bulkRequest, RequestOptions.DEFAULT);

    }
}